package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
import android.view.View
import android.webkit.*
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.zhiyou.aifeng.common.base.makeCall
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.optNotNull
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.common_ui.viewmodel.BaseViewModel
import org.jetbrains.anko.browse
import org.jetbrains.anko.webView
import org.json.JSONObject

@Route(path = Routers.deal)
class WebActivity : BaseActivity() {

    private lateinit var mWeb: WebView

    @JvmField
    @Autowired(name = "title")
    var mTitle: String = ""

    @JvmField
    @Autowired(name = "hint")
    var mHint: String = ""

    @JvmField
    @Autowired(name = "time")
    var mTime: String = ""

    @JvmField
    @Autowired(name = "content")
    var mContent: String = ""

    @SuppressLint("SetJavaScriptEnabled")
    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        mWeb = webView {
            overScrollMode = View.OVER_SCROLL_NEVER

            //支持javascript
            settings.javaScriptEnabled = true
            //设置可以支持缩放
            settings.setSupportZoom(true)
            //自适应屏幕
            settings.loadWithOverviewMode = true
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            isHorizontalScrollBarEnabled = false

            //设置出现缩放工具
            settings.builtInZoomControls = false
            settings.displayZoomControls = false

            //设置是否使用缓存
            settings.setAppCacheEnabled(true)
            settings.domStorageEnabled = true

            webChromeClient = WebChromeClient()
            webViewClient = object : WebViewClient() {

                /*
                 * 当加载的网页需要重定向的时候就会回调这个函数告知我们应用程序是否需要接管控制网页加载，
                 * 如果应用程序接管，并且return true意味着主程序接管网页加载，如果返回false让webview自己处理
                 */
                @Suppress("DEPRECATION", "OverridingDeprecatedMember")
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return when {
                        "tel:" in url -> makeCall(url.replace("tel:", ""))
                        !url.startsWith("https://")
                                && !url.startsWith("http://") -> {
                            if (url.startsWith("weixin://wap/pay?")) browse(url)
                            true
                        }
                        url.endsWith(".apk") -> browse(url)
                        else -> {
                            view.loadUrl(url)
                            true
                        }
                    }
                }

                /*
                 * 在开始加载网页时会回调
                 */
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    showLoading()
                }

                /*
                 * 在结束加载网页时会回调
                 */
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    dismissLoading()
                }

                /*
                 * 当网页加载资源过程中发现SSL错误会调用此方法。
                 * 我们应用程序必须做出响应，是取消请求handler.cancel(),
                 * 还是继续请求handler.proceed(),
                 * 内核的默认行为是handler.cancel()
                 */
                override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler?,
                    error: SslError?
                ) {
                    handler?.proceed() ?: super.onReceivedSslError(view, handler, error)
                }

            }
        }
        initTitle(title = mTitle)

        if (mTitle == "详情") {
            val str = "<!doctype html><html>\n" +
                    "<meta charset=\"utf-8\">" +
                    "<style type=\"text/css\">" +
                    "body{ padding:0; margin:0; }\n" +
                    ".view_h1{ width:90%; margin:0 auto; font-size:1.1em; color:#333; padding:0.8em 0; line-height:1.8em; }\n" +
                    ".view_time{ width:90%; margin:0 auto; font-size:0.8em; color:#999; }\n" +
                    ".con{ width:90%; margin:0 auto; color:#666; padding:0.8em 0; font-size:0.95em; line-height:1.8em; }\n" +
                    ".con h1,h2,h3,h4,h5,h6{ font-size:1em; }\n " +
                    "img{ width:100%; height:auto; }\n" +
                    "*{ max-width:100% !important; }\n" +
                    "</style>\n" +
                    "<body style=\"padding:0; margin:0; \">" +
                    "<div class=\"view_h1\">" +
                    mHint +
                    "</div>" +
                    "<div class=\"view_time\" style=\"border-bottom:0.5px solid #e8e8e8; padding-bottom:15px;\">" +
                    mTime +
                    "</div>" +
                    "<div class=\"con\">" +
                    mContent +
                    "</div>" +
                    "</body>" +
                    "</html>"

            mWeb.loadDataWithBaseURL("", str, "text/html", "utf-8", "")
        }
        else getData()
    }

    override fun getViewModel() = get<BaseViewModel>()

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().request(
            requestUrl = BaseUrl.other,
            params = *arrayOf(
                "type" to when (mTitle) {
                    "用户协议", "平台使用协议" -> "driverAgree"
                    "申请使用说明" -> "applyTeam"
                    "关于我们" -> "aboutus"
                    "隐私政策" -> "privacy"
                    else -> ""
                }
            )
        ) {
            val obj = JSONObject(it)

            val str = "<!doctype html><html>\n" +
                    "<meta charset=\"utf-8\">" +
                    "<style type=\"text/css\">" +
                    "body{ padding:0; margin:0; }\n" +
                    ".con{ width:95%; margin:0 auto; color:#666; padding:0.5em 0; font-size:0.95em; line-height:1.8em; }\n" +
                    ".con h1,h2,h3,h4,h5,h6{ font-size:1em; }\n " +
                    "img{ width:100%; height:auto; }\n" +
                    "*{ max-width:100% !important; }\n" +
                    "</style>\n" +
                    "<body style=\"padding:0; margin:0; \">" +
                    "<div class=\"con\">" +
                    obj.optNotNull("content") +
                    "</div>" +
                    "</body>" +
                    "</html>"

            mWeb.loadDataWithBaseURL("", str, "text/html", "utf-8", "")
        }
    }

    override fun onResume() {
        super.onResume()
        mWeb.onResume()
    }

    override fun onPause() {
        super.onPause()
        mWeb.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mWeb.destroy()
    }

    override fun onBackPressed() {
        if (mWeb.canGoBack()) mWeb.goBack()
        else super.onBackPressed()
    }

}
